<?php
namespace App\Http\Middleware;

use Closure;

class CORS {

    /** 添加laravel5.4 跨域请求
     * 处理请求.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {

        //设置允许来源头信息：Access-COntrol-Allow-Origin
        header("Access-Control-Allow-Origin: http://192.168.48.1:8081");

        // 设置允许请求的方法
        $headers = [
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization'
        ];

        if ($request->getMethod() == "OPTIONS") {
            // 对于预请求返回200
            return \Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach ($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }
}